import type { Router } from 'vue-router'

import { Role } from '@/constants/role'
import { RouterName } from '@/router/name'
import { useUserStore } from '@/stores/user'
import { buildRedirectLoginLocation } from '@/router/redirect-login'

export function authGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    if (to.meta.requireAuth === false) {
      return next()
    }

    const userStore = useUserStore()

    if (userStore.hasLogin) {
      const hasUserProfile = userStore.user.role !== Role.None

      if (hasUserProfile || (await userStore.updateUserInfo())) {
        const isAllowed = userStore.isEnabled(to.meta.role ?? Role.None)
        return isAllowed ? next() : next({ name: RouterName.Forbidden })
      }

      userStore.logout()
    }

    next(buildRedirectLoginLocation(to))
  })
}
